package com.example.test_witns.ui.mine;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.test_witns.BottomNavigationViewActivity;
import com.example.test_witns.R;
import com.example.test_witns.databinding.FragmentMineBinding;
import com.example.test_witns.ui.login.LoginActivity;
import com.example.test_witns.ui.mine.blogs.BlogsLikedActivity;
import com.example.test_witns.ui.mine.blogs.BlogsStaredActivity;
import com.example.test_witns.ui.mine.blogs.BlogsViewLaterActivity;
import com.example.test_witns.ui.mine.blogs.BlogsViewedActivity;
import com.example.test_witns.ui.mine.more.MoreAboutActivity;
import com.example.test_witns.ui.mine.more.MoreDevelopAdviseActivity;
import com.example.test_witns.ui.mine.more.MoreFeedbackActivity;
import com.example.test_witns.ui.mine.more.MoreSettingsActivity;
import com.example.test_witns.ui.mine.organizations.OrganizationEstablishActivity;
import com.example.test_witns.ui.mine.organizations.OrganizationIssuesActivity;
import com.example.test_witns.ui.mine.organizations.OrganizationJoinActivity;
import com.example.test_witns.ui.mine.organizations.OrganizationManagementActivity;
import com.example.test_witns.ui.mine.organizations.OrganizationsActivity;
import com.example.test_witns.ui.mine.skills.SkillCareerActivity;
import com.example.test_witns.ui.mine.skills.SkillCurriculumVitaeActivity;
import com.example.test_witns.ui.mine.skills.SkillFieldIdentificationActivity;
import com.example.test_witns.ui.mine.skills.SkillGrowthManagementActivity;
import com.example.test_witns.ui.mine.skills.SkillHonorWallActivity;
import com.example.test_witns.ui.mine.skills.SkillTagsManagementActivity;
import com.example.test_witns.ui.mine.skills.SkillTreeActivity;
import com.example.test_witns.ui.my_qrcode.MyQRCodeActivity;
import com.example.test_witns.utils.GlideEngine;
import com.example.test_witns.utils.MyInfosHelper;
import com.example.test_witns.utils.OssUtil;
import com.google.android.material.navigation.NavigationView;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CropFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMSDKConfig;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.yalantis.ucrop.UCrop;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import de.hdodenhof.circleimageview.CircleImageView;

public class MineFragment extends Fragment {
    private FragmentMineBinding binding;
    private TextView my_username;
    private TextView my_uuid;
    private CircleImageView my_avatar;
    private String sig;
    private static byte[] imageBytes;
    private String avatarURI;
    private String avatarURL;
    private String email;
    private Intent intent;
    private DrawerLayout mDrawerLayout;
    private NavigationView mine_drawer_nav_view;

    private static final int NAV_LOGOUT = R.id.logout;
    private static final int NAV_FEEDBACK = R.id.nav_feedback;

    String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    String accessKeyId = "LTAI5tMMT1mKsUbjgvunz56D";
    String accessKeySecret = "BxCzPRF4aTosxFnfrIZzAmLdatjoGV";
    String bucketName = "fftechuseravater";

    private ActivityResultLauncher<Intent> mGetContentLauncher;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentMineBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        initRedirectListener(root);

        root.findViewById(R.id.change_light_mode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = "darkmode developing, not available now.";
                toast_Prohibited_Style(message);
            }
        });

        OSSLog.enableLog();

        NavController navController = NavHostFragment.findNavController(this);

        mDrawerLayout = root.findViewById(R.id.mine_drawer_layout);
        mine_drawer_nav_view = root.findViewById(R.id.mine_drawer_nav_view);
        // 设置ActionBarDrawerToggle
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                getActivity(), mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        // 设置NavigationView的菜单项点击监听
        mine_drawer_nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == NAV_LOGOUT) {// 处理Home点击事件
                    new AlertDialog.Builder(getContext())
                            .setTitle("I QUIT")
                            .setMessage("您确定要退出登录吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    V2TIMManager.getInstance().logout(new V2TIMCallback() {
                                        @Override
                                        public void onSuccess() {
                                            Toast.makeText(getContext(), "退出成功", Toast.LENGTH_SHORT).show();
                                            try (MyInfosHelper myInfosHelper = new MyInfosHelper(getContext())) {
                                                myInfosHelper.deleteMyInfosTable();
                                                BottomNavigationViewActivity.onLogin = false;
                                            }
                                            Intent intent = new Intent(getContext(), LoginActivity.class);
                                            startActivity(intent);
                                        }

                                        @Override
                                        public void onError(int i, String s) {

                                        }
                                    });
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 用户点击取消按钮后的操作，通常不做任何操作
                                    dialog.dismiss();
                                }
                            })
                            .setIcon(R.drawable.run_foreground)
                            .show();
                } else if (itemId == R.id.nav_feedback) {// 处理Gallery点击事件

                }else {

                }

                return true;
            }
        });

        // 假设您有一个按钮来触发侧边栏的打开
        root.findViewById(R.id.mine_more).setOnClickListener(view -> mDrawerLayout.openDrawer(GravityCompat.END));

        mGetContentLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent data = result.getData();
                    Uri imageUri = data.getData();
                    if (imageUri != null) {

                        // 处理获取到的图片URI
                        // 例如，将其设置到ImageView或者进行其他处理
                        my_avatar.setImageURI(imageUri);
                        MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());
                        byte[] bytesFromImageUri = getBytesFromImageUri(getContext(), imageUri);
                        boolean isUpdated = myInfosHelper.updateAvatarByName(myInfosHelper.getMyUserId(), bytesFromImageUri);
                        imageBytes = myInfosHelper.getAvatarByName(myInfosHelper.getMyUserId());
                        if (imageBytes != null){
                            Toast.makeText(getContext(), "更新成功", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(getContext(), "失败", Toast.LENGTH_SHORT).show();
                        }
                        avatarURI = imageUri.toString();
                        email = myInfosHelper.getMyUserId();
                        avatarURL = email + UUID.randomUUID().toString() + ".jpg";

                        uploadImageToOSS("fftechuseravater", "images/userIcon/" + avatarURL, null, imageUri);

                    }
                }
            }
        );

        my_username = root.findViewById(R.id.username_mine);
        my_uuid = root.findViewById(R.id.uuid_value_mine);
        my_avatar = root.findViewById(R.id.avatar_mine);
        View space_mine = root.findViewById(R.id.space_mine);

        Window window = getActivity().getWindow();
        window.setStatusBarColor(Color.parseColor("#eeeeee"));

        MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());
        boolean isLogin = myInfosHelper.checkIfLogin();
        if (isLogin && !BottomNavigationViewActivity.onLogin){
            myInfosHelper.loadMyInfos(new MyInfosHelper.GetMyInfos() {
                @Override
                public void onLoadingMyInfos(String email ,String sig, String name, String uuid, byte[] avatar, String uri, String url) {
                    my_username.setText(name);
                    my_uuid.setText(uuid);

                    V2TIMSDKConfig config = new V2TIMSDKConfig();
                    config.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_INFO);
                    V2TIMManager.getInstance().initSDK(getContext(),1600066337, config);

                    V2TIMManager.getInstance().login(email, sig, new V2TIMCallback() {
                        @Override
                        public void onSuccess() {
                            myInfosHelper.loadMyInfos(new MyInfosHelper.GetMyInfos() {
                                @Override
                                public void onLoadingMyInfos(String email ,String sig, String name, String uuid, byte[] avatar, String uri, String url) {
                                    my_username.setText(name);
                                    my_uuid.setText(uuid);
                                    if (imageBytes == null){
                                        MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());
                                        imageBytes = myInfosHelper.getAvatarByName(myInfosHelper.getMyUserId());
                                        if (imageBytes != null){

                                        }else {
                                            ArrayList<String> userId = new ArrayList<>();
                                            userId.add(myInfosHelper.getMyUserId());
                                            V2TIMManager.getInstance().getUsersInfo(userId, new V2TIMValueCallback<List<V2TIMUserFullInfo>>() {
                                                @Override
                                                public void onSuccess(List<V2TIMUserFullInfo> v2TIMUserFullInfos) {
                                                    for (V2TIMUserFullInfo userinfo :
                                                            v2TIMUserFullInfos) {
                                                        String faceUrl = userinfo.getFaceUrl();
                                                        if (faceUrl != null){
                                                            Glide.with(requireContext())
                                                                    .load(faceUrl)
                                                                    .listener(new RequestListener<Drawable>() {
                                                                        @Override
                                                                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                                                            return false;
                                                                        }

                                                                        @Override
                                                                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                                                            Bitmap bitmap1 = null;
                                                                                bitmap1 = ((BitmapDrawable)resource).getBitmap();
                                                                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                                                                bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                                                                                imageBytes = outputStream.toByteArray();
                                                                                myInfosHelper.updateAvatarByName(myInfosHelper.getMyUserId(), imageBytes);
                                                                            return false;
                                                                        }
                                                                    })
                                                                    .into(my_avatar);
                                                            myInfosHelper.updateMyAvatarURL(myInfosHelper.getMyUserId(), faceUrl);
                                                        }else {
                                                            Toast.makeText(getContext(), "未设置头像", Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                }
                                                @Override
                                                public void onError(int i, String s) {

                                                }
                                            });
                                        }
                                    }
                                    if (imageBytes != null) {
                                        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                                        my_avatar.setImageBitmap(bitmap);
                                    }
                                }
                            });
                            my_avatar.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // 启动图片选择器，设置为单选模式
                                    PictureSelector.create(getContext())
                                            .openGallery(SelectMimeType.ofImage()) // 只打开图片选择
                                            .setCropEngine(new CropFileEngine() {
                                                @Override
                                                public void onStartCrop(Fragment fragment, Uri srcUri, Uri destinationUri, ArrayList<String> dataSource, int requestCode) {
                                                    UCrop.Options options = new UCrop.Options();
                                                    options.setCircleDimmedLayer(true);
                                                    UCrop uCrop = UCrop.of(srcUri, destinationUri ,dataSource).withOptions(options);
                                                    uCrop.start(fragment.getActivity(), fragment, requestCode);
                                                }
                                            })
                                            .setMaxSelectNum(1) // 设置最大选择图片数量为1
                                            .setImageEngine(GlideEngine.createGlideEngine())
                                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                                @Override
                                                public void onResult(ArrayList<LocalMedia> result) {
                                                    // 处理选择结果
                                                    if (!result.isEmpty()) {
                                                        LocalMedia media = result.get(0);
                                                        if (media != null){
                                                            ContentResolver contentResolver = getContext().getContentResolver();
                                                            Uri imageUri = Uri.parse(media.getPath());
                                                            if (imageUri != null) {
                                                                // 处理获取到的图片URI
                                                                // 例如，将其设置到ImageView或者进行其他处理
                                                                my_avatar.setImageURI(imageUri);
                                                                MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());
                                                                byte[] bytesFromImageUri = getBytesFromImageUri(getContext(), imageUri);
                                                                boolean isUpdated = myInfosHelper.updateAvatarByName(myInfosHelper.getMyUserId(), bytesFromImageUri);
                                                                imageBytes = myInfosHelper.getAvatarByName(myInfosHelper.getMyUserId());
                                                                if (imageBytes != null){
                                                                    Toast.makeText(getContext(), "更新成功", Toast.LENGTH_SHORT).show();
                                                                }else {
                                                                    Toast.makeText(getContext(), "失败", Toast.LENGTH_SHORT).show();
                                                                }
                                                                avatarURI = imageUri.toString();
                                                                String current_email = myInfosHelper.getMyUserId();
                                                                avatarURL = current_email + UUID.randomUUID().toString() + ".jpg";
                                                                myInfosHelper.updateMyAvatarURL(myInfosHelper.getMyUserId(),avatarURL);

                                                                uploadImageToOSS("fftechuseravater", "images/userIcon/" + avatarURL, null, imageUri);

                                                            }
                                                        }
                                                        // 使用uri进行下一步操作，例如上传图片等
                                                    }
                                                }

                                                @Override
                                                public void onCancel() {
                                                    // 处理取消事件
                                                }
                                            });
                                }
                            });
                        }

                        @Override
                        public void onError(int i, String s) {
                            Toast.makeText(getContext(), "登录时出现异常,请重新登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        } else if (isLogin && BottomNavigationViewActivity.onLogin) {
            myInfosHelper.loadMyInfos(new MyInfosHelper.GetMyInfos() {
                @Override
                public void onLoadingMyInfos(String email ,String sig, String name, String uuid, byte[] avatar, String uri, String url) {
                    my_username.setText(name);
                    my_uuid.setText(uuid);
                    if (imageBytes == null){

                        MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());
                        imageBytes = myInfosHelper.getAvatarByName(myInfosHelper.getMyUserId());
                        if (imageBytes != null){

                        }else {
                            ArrayList<String> userId = new ArrayList<>();
                            userId.add(myInfosHelper.getMyUserId());
                            V2TIMManager.getInstance().getUsersInfo(userId, new V2TIMValueCallback<List<V2TIMUserFullInfo>>() {
                                @Override
                                public void onSuccess(List<V2TIMUserFullInfo> v2TIMUserFullInfos) {
                                    for (V2TIMUserFullInfo userinfo :
                                            v2TIMUserFullInfos) {
                                        String faceUrl = userinfo.getFaceUrl();
                                        if (faceUrl != null){
                                            Glide.with(requireContext())
                                                    .load(faceUrl)
                                                    .listener(new RequestListener<Drawable>() {
                                                        @Override
                                                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                                            return false;
                                                        }

                                                        @Override
                                                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                                            Bitmap bitmap1 = null;
                                                                bitmap1 = ((BitmapDrawable)resource).getBitmap();
                                                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                                                bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                                                                imageBytes = outputStream.toByteArray();
                                                                myInfosHelper.updateAvatarByName(myInfosHelper.getMyUserId(), imageBytes);
                                                            return false;
                                                        }
                                                    })
                                                    .into(my_avatar);
                                            myInfosHelper.updateMyAvatarURL(myInfosHelper.getMyUserId(), faceUrl);
                                        }else {
                                            Toast.makeText(getContext(), "未设置头像", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                                @Override
                                public void onError(int i, String s) {

                                }
                            });
                        }
                    }
                    if (imageBytes != null) {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                        my_avatar.setImageBitmap(bitmap);
                    }
                }
            });

            my_avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // 启动图片选择器，设置为单选模式
                    PictureSelector.create(getContext())
                            .openGallery(SelectMimeType.ofImage()) // 只打开图片选择
                            .setCropEngine(new CropFileEngine() {
                                @Override
                                public void onStartCrop(Fragment fragment, Uri srcUri, Uri destinationUri, ArrayList<String> dataSource, int requestCode) {
                                    UCrop.Options options = new UCrop.Options();
                                    options.setCircleDimmedLayer(true);
                                    UCrop uCrop = UCrop.of(srcUri, destinationUri ,dataSource).withOptions(options);
                                    uCrop.start(fragment.getActivity(), fragment, requestCode);
                                }
                            })
                            .setMaxSelectNum(1) // 设置最大选择图片数量为1
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    // 处理选择结果
                                    if (!result.isEmpty()) {
                                        LocalMedia media = result.get(0);
                                        if (media != null){
                                            ContentResolver contentResolver = getContext().getContentResolver();
                                            Uri imageUri = Uri.parse(media.getPath());
                                            if (imageUri != null) {
                                                // 处理获取到的图片URI
                                                // 例如，将其设置到ImageView或者进行其他处理
                                                my_avatar.setImageURI(imageUri);
                                                MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());
                                                byte[] bytesFromImageUri = getBytesFromImageUri(getContext(), imageUri);
                                                boolean isUpdated = myInfosHelper.updateAvatarByName(myInfosHelper.getMyUserId(), bytesFromImageUri);
                                                imageBytes = myInfosHelper.getAvatarByName(myInfosHelper.getMyUserId());
                                                if (imageBytes != null){
                                                    Toast.makeText(getContext(), "更新成功", Toast.LENGTH_SHORT).show();
                                                }else {
                                                    Toast.makeText(getContext(), "失败", Toast.LENGTH_SHORT).show();
                                                }
                                                avatarURI = imageUri.toString();
                                                String current_email = myInfosHelper.getMyUserId();
                                                avatarURL = current_email + UUID.randomUUID().toString() + ".jpg";
                                                myInfosHelper.updateMyAvatarURL(myInfosHelper.getMyUserId(), avatarURL);

                                                uploadImageToOSS("fftechuseravater", "images/userIcon/" + avatarURL, null, imageUri);

                                            }
                                        }

                                    }
                                }

                                @Override
                                public void onCancel() {
                                    // 处理取消事件
                                }
                            });
                }
            });

        }else {
            toast_Prohibited_Style("未登录");
            my_avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                }
            });
        }

        return root;
    }

    private void toast_Prohibited_Style(String message) {
        View customView = LayoutInflater.from(getContext()).inflate(R.layout.custom_toast_prohibited_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(getContext());
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 40); // 设置在屏幕顶部
        toast.show();
    }

    private void initRedirectListener(View root) {
        MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());
        setRedirectListener(root.findViewById(R.id.my_liked_blogs), BlogsLikedActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_stared_blogs), BlogsStaredActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_viewed_blogs), BlogsViewedActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_view_later_blogs), BlogsViewLaterActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_organization_establish), OrganizationEstablishActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_organization_issues), OrganizationIssuesActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_organization_join), OrganizationJoinActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_organization_management), OrganizationManagementActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_organizations), OrganizationsActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_skills_career), SkillCareerActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_skills_curriculum_vitae), SkillCurriculumVitaeActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_skills_feild_identification), SkillFieldIdentificationActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_skills_growth_management), SkillGrowthManagementActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_skills_honor_wall), SkillHonorWallActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_skills_tags_management), SkillTagsManagementActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_skills_tree), SkillTreeActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_more_feedback), MoreFeedbackActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_more_develop_advise), MoreDevelopAdviseActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_more_settings), MoreSettingsActivity.class, "");
        setRedirectListener(root.findViewById(R.id.my_more_about), MoreAboutActivity.class, "");
        if (myInfosHelper.checkIfLogin()){
            List<String> list = new ArrayList<String>();
            list.add(myInfosHelper.getMyNickname());
            list.add(myInfosHelper.getMyUserId());
            list.add(myInfosHelper.getMyUUID());
            list.add(myInfosHelper.getMyAvatarURL());
            setRedirectListener(root.findViewById(R.id.my_qr_code), MyQRCodeActivity.class, myInfosHelper.getAvatarByName(myInfosHelper.getMyUserId()), list);
        }else {
            root.findViewById(R.id.my_qr_code).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toast_Prohibited_Style("您尚未登录");
                }
            });
        }

    }

    private void launchGetContent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        mGetContentLauncher.launch(intent);
    }

    public String getRealPathFromURI(Context context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        cursor.close();
        return path;
    }

    public byte[] getBytesFromImageUri(Context context, Uri imageUri) {
        String path = getRealPathFromURI(context, imageUri);
        byte[] byteArray = null;
        try {
            FileInputStream fileInputStreamReader = new FileInputStream(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int n;
            while ((n = fileInputStreamReader.read(buffer)) != -1) {
                output.write(buffer, 0, n);
            }
            fileInputStreamReader.close();
            byteArray = output.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArray;
    }

    /* 图片压缩 */
    private byte[] compressImage(byte[] imageBytes) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2; // 图片压缩比例
        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bao);
        return bao.toByteArray();
    }

    public void uploadFile(String bucketName, String objectKey, String filePath) {

    }

    public void uploadImageToOSS(String bucketName, String objectName, byte[] imageBytes, Uri uri) {
        OSS ossClient = OssUtil.initOSS(getContext(), endpoint, accessKeyId, accessKeySecret, bucketName);
        try {
            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, uri);

            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 打印结果
            if (result != null) {
                // 上传成功
                V2TIMUserFullInfo v2TIMUserFullInfo = new V2TIMUserFullInfo();
                v2TIMUserFullInfo.setFaceUrl("https://fftechuseravater.oss-cn-beijing.aliyuncs.com/images/userIcon/" + avatarURL);
                V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo, new V2TIMCallback() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(getContext(), "头像同步成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });
            } else {
                // 上传失败
                System.out.println("Upload Failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    public void setRedirectListener(View listenerView, Class c, String argumentString){
        listenerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getContext(), c);
                intent.putExtra("argumentString", argumentString);
                startActivity(intent);
            }
        });
    }

    public void setRedirectListener(View listenerView, Class c, byte[] argumentBytes){
        listenerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getContext(), c);
                intent.putExtra("argumentBytes", argumentBytes);
                startActivity(intent);
            }
        });
    }

    public void setRedirectListener(View listenerView, Class c, byte[] argumentBytes, String argumentString){
        listenerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getContext(), c);
                intent.putExtra("argumentBytes", argumentBytes);
                intent.putExtra("argumentString", argumentString);
                startActivity(intent);
            }
        });
    }

    public void setRedirectListener(View listenerView, Class c, byte[] argumentBytes, List<String> argumentStrings){
        listenerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getContext(), c);
                intent.putExtra("argumentBytes", argumentBytes);
                int argumentStringCounter = 1;
                for(String argumentString : argumentStrings){
                    intent.putExtra("argumentString" + argumentStringCounter++, argumentString);
                }
                startActivity(intent);
            }
        });
    }

    public void showToastAboveView(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_confirm_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }

}
